import functools
# 装饰器 在代码运行期间动态增加功能的方式

def log(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator


@log('execute')
def today():
    print('2025-08-22')
print(today.__name__)
print(today())

# 观察到上述 now 函数的__name__属性已经发生了变化，变成了 wrapper，如果想要保持原来的函数名称不变，需要加上@functools.wraps(func)注解
def log(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator


@log('execute')
def today():
    print('2025-08-22')
print(today.__name__)
print(today()) # now函数没有返回值，因此 print 的话会打印 none


import time, functools

def metric(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kw):
        start = time.time()
        result = fn(*args, **kw)
        duration = time.time() - start
        print('%s executed in %f s' % (fn.__name__, duration))
        return result
    return wrapper

# 测试
@metric
def fast(x, y):
    time.sleep(0.0012)
    return x + y

@metric
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z

f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
    print('测试失败!')
elif s != 7986:
    print('测试失败!')

def write_log(func):
    def wrapper(*args, **kw):
        print("begin call")
        print("%s executed" % func.__name__)
        result = func(*args, **kw)
        print("end call")
        return result
    return wrapper

@write_log
def fast(x, y):
    time.sleep(0.0012)
    return x + y

@write_log
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z
print(fast(11, 22))
print(slow(11, 22, 33))

def log_new(*text):
    def decorator(func):
        def wrapper(*args, **kw):
            if len(text) == 0 or text == None :
                print("%s 没有text参数传进来" % func.__name__)
            result = func(*args, **kw)
            return result
        return wrapper
    return decorator

@log_new
def fast(x, y):
    time.sleep(0.0012)
    return x + y

@log_new
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z
f = fast(11, 22)
s = slow(11, 22, 33)